package com.example.jetpacktest.room

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import com.example.jetpacktest.R

class RoomActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_room)

        var dao = AppDatabase.getInstance(this).userDao()

        Thread(Runnable {
            try {
                //        插入对象
                for (i in 0..4) {
                    var user = User(userName = "张三${i}", address = "河南", sex = true, userId = i)
                    dao.insertUser(user)
                }

                var info = dao.getUserById(1)
                Log.e("!!!!!!!!", "${info.userId}--${info.userName}--${info.address}")

                dao.updateUser(User(userId = 1, userName = "张三", address = "河南", sex = true))

                var info2 = dao.getUserById(1)
                Log.e("!!!!!!!!", "${info2.userId}--${info2.userName}--${info2.address}")

                dao.deleteUser(User(userId = 1, userName = "张三", address = "河南", sex = true))
                var info3 = dao.getUserById(2)
                Log.e("!!!!!!!!", "${info3?.userId}--${info3?.userName}--${info3?.address}")

            } catch (e: Exception) {
                Log.e("!!!!!", "")
            }


        }).start()

        try {
            var viewModel = ViewModelProvider(this).get(StudentViewModel::class.java)
            viewModel.getLiveDataStudent()?.observe(this, Observer<List<Student>> { list ->
                list?.forEach {
                    Log.e("!!!!!!!!!!!!!viewmodel", it.name)
                }
            })

            Thread(Runnable {
                var dao1 = AppDatabase.getInstance(this).studentDao()
                dao1.insertStudent(Student(id = 1, name = "李四"))
            }).start()

        } catch (e: Exception) {
            Log.e("!!!!!", "")
        }

    }
}
